﻿var makeSureQuilty = {
    'qulity_service_price': '服务站',
    'qulity_org_price': '原厂原包',
    'qulity_matching_price': '配套',
    'qulity_complete_price': '品牌',
    'qulity_suitable_price': '适用',
}

function init() {
    var curr_time = new Date();
    $('#dts').datetimebox({
        value: dtsformatter(curr_time),
        required: true,
        showSeconds: true
    });
    $('#dte').datetimebox({
        value: dteformatter(curr_time),
        required: true,
        showSeconds: true
    });
}

function dtsformatter(date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    var d = date.getDate();
    return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d);
}

function dteformatter(date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    var d = date.getDate();
    var hh = date.getHours();
    var mm = date.getMinutes();
    var ss = date.getMilliseconds();
    return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d) + " " + (hh < 10 ? ('0' + hh) : hh) + ":" + (mm < 10 ? ('0' + mm) : mm) + ":" + (ss < 10 ? ('0' + ss) : ss);
}

//var access_baseurl = "http://localhost:88/tp5/public/index.php/gongre/";
// var access_baseurl = "http://60.223.229.39:50001/tp5/public/index.php/gongre/";

// var access_baseurl = location.protocol+"//"+location.host+"/htqipei/htapi/public/index.php/company/";
 var access_baseurl = "http://localhost/qipei/htapi/public/index.php/company/";

// function a(){
//     sessionStorage.setItem("bendi","1");
//     access_baseurl = "http://192.168.10.7:88/tp5/public/index.php/gongre/";
//     return "操作成功!";
// }
//
// if(sessionStorage.getItem("bendi") == "1"){
//     access_baseurl = "http://192.168.10.7:88/tp5/public/index.php/gongre/";
// }

var pTimer = null;



function handleInput(obj,ef) {
    //防止多次触发事件
    if (pTimer) clearTimeout(pTimer)
    pTimer = setTimeout(() => {
        ef();
        console.log($(obj).val());
        pTimer = null;
    }, 1000)
}

/**
 * 发送ajax请求
 * @param {Object} purl      请求地址
 * @param {Object} jsonparam json参数
 * @param {Object} succfun 成功后处理函数
 * @param {Object} pasync  同步或者异步 默认true异步
 */
function send_req(purl, jsonparam, succfun, pasync) {
    var url = access_baseurl + purl;

    var userStr = sessionStorage.getItem("gysuname");

    if (userStr) {
        var userObj = JSON.parse(userStr);
        jsonparam.opt_user_id = userObj.id;
        jsonparam.opt_user_name = userObj.contact_person_name;

        if(!is_write(userObj,purl)){
            return;
        }
    }

    if (pasync !== false && !pasync) {
        pasync = true;
    }
    $.ajax({
        url: url,
        type: 'POST',
        dataType: 'JSON',
        async: pasync,
        data: jsonparam,
        success: function (data) {
            // console.log(url+JSON.stringify(jsonparam));
            if (data.success === undefined || data.success === true) {
                succfun(data.obj);
            } else {
                layer.closeAll('loading');
                layer.msg(data.msg, { icon: 2, anim: 6 });
                //alert(data.msg);
                $('.site-demo-active').removeClass('layui-btn-disabled');
                $('.site-demo-active').removeAttr('disabled');
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            layer.closeAll('loading');
            layer.msg('error', { icon: 2, anim: 6 });
            //alert(data.msg);
            $('.site-demo-active').removeClass('layui-btn-disabled');
            $('.site-demo-active').removeAttr('disabled');
            // console.log("ajax错误类型："+textStatus+url);
            // console.log(errorThrown);

//				 alert(XMLHttpRequest.status);
            // alert(XMLHttpRequest.readyState);
//				 alert(textStatus);
        }
    });
}


function new_send_req(purl, jsonparam, succfun, pasync) {
    var url = access_baseurl + purl;

    var userStr = sessionStorage.getItem("uanme");
    if (userStr) {
        var userObj = JSON.parse(userStr);
        jsonparam.opt_user_id = userObj.user_id;
        jsonparam.opt_user_name = userObj.true_name;

        if(!is_write(userObj,purl)){
            return;
        }
    }

    if (pasync !== false && !pasync) {
        pasync = true;
    }
    $.ajax({
        url: url,
        type: 'POST',
        dataType: 'JSON',
        async: pasync,
        data: jsonparam,
        success: function (data) {
            succfun(data);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            // console.log("ajax错误类型："+textStatus+url);
            // console.log(errorThrown);

//				 alert(XMLHttpRequest.status);
            // alert(XMLHttpRequest.readyState);
//				 alert(textStatus);
        }
    });
}

function is_write(userObj,purl){
    if(userObj.is_write == '0'){
        //说明是只读,增加权限控制
        var re = /^Siteconfig\//;

        if((re.test(purl) && purl != "Siteconfig/detail" && purl != "Siteconfig/detail_by_sitemapno") || purl == "Siteconfig/update_time_setting" || purl=="Position/position_add"
            || purl == "Hottime/save_hot_time" || purl == "Tjfcontrol/set_tjf_control"){

            alert("当前账号没有权限!");
            layer.closeAll();
            return false;
        }

    }

    return true;
}

/**
 * 获取URL地址参数
 * @param {Object} parmname   参数名称
 */
function GetQueryString(parmname) {
    var reg = new RegExp("(^|&)" + parmname + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}


function round(num, pointLen) {
    return Math.round(num * 1000) / 1000
}

function formatNum(num){//51548
    var result = parseFloat(num);
    if (isNaN(result)) {
        return "0.00";
    }
    result = Math.round(num * 100) / 100;
    var s_x = result.toString();
    var pos_decimal = s_x.indexOf('.');
    if (pos_decimal < 0) {
        pos_decimal = s_x.length;
        s_x += '.';
    }
    while (s_x.length <= pos_decimal + 2) {
        s_x += '0';
    }
    return s_x;
}

//除法
function floatDiv(arg1,arg2){
    var t1=0,t2=0,r1,r2;
    try{t1=arg1.toString().split(".")[1].length}catch(e){}
    try{t2=arg2.toString().split(".")[1].length}catch(e){}
    with(Math){
        r1=Number(arg1.toString().replace(".",""))
        r2=Number(arg2.toString().replace(".",""))
        return accMul((r1/r2),pow(10,t2-t1));
    }
}
//乘法
function floatMul(arg1,arg2) {
    var m=0,s1=arg1.toString(),s2=arg2.toString();
    try{m+=s1.split(".")[1].length}catch(e){}
    try{m+=s2.split(".")[1].length}catch(e){}
    return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
}

// //减法
// function  floatSub(arg1,arg2){
//     return floatAdd(arg1,"-"+arg2.toString());
// }

//保留n位小数
function roundFun(value, n) {
    return Math.round(value*Math.pow(10,n))/Math.pow(10,n);
}

//减法
function floatSub(arg1,arg2){
    var r1,r2,m,n;
    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
    m=Math.pow(10,Math.max(r1,r2));
    n=(r1>=r2)?r1:r2;
    // return ((arg1*m-arg2*m)/m).toFixed(n);
    return round(((arg1*m-arg2*m)/m),n);
}

//加法
function floatAdd(arg1,arg2){
    var r1,r2,m;
    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
    m=Math.pow(10,Math.max(r1,r2));
    return (arg1*m+arg2*m)/m;
}


function getSiteWay(num){
    var siteWayObj = {
        1:"东线",
        2:"西线",
        3:"北线",
        4:"地暖"
    };
    //管线 1:东线 2:西线 3:北线 4:地暖

    return siteWayObj[num];
}

(function (owner) {
    /**
     * 获取当前状态
     **/
    owner.getState = function () {
        var stateText = localStorage.getItem('$state') || "{}";
        return JSON.parse(stateText);
    };

    /**
     * 设置当前状态
     **/
    owner.setState = function (state) {
        state = state || {};
        localStorage.setItem('$state', JSON.stringify(state));
    };
}(window.app = {}));

/**
 根据参数名获取URL地址参数
 */
function getQueryString(name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    };
    return null;
}

/**
 * 获取当前时间，可指定格式:yyyy-MM-dd hh:mm:ss
 */
Date.prototype.dateFormat = function (format){
    var o = {
        "M+" : this.getMonth()+1, //month
        "d+" : this.getDate(), //day
        "h+" : this.getHours(), //hour
        "m+" : this.getMinutes(), //minute
        "s+" : this.getSeconds(), //second
        "q+" : Math.floor((this.getMonth()+3)/3), //quarter
        "S" : this.getMilliseconds() //millisecond
    }
    if(/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    }
    for(var k in o) {
        if(new RegExp("("+ k +")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
        }
    }
    return format;
}

/**
 * 求百分比
 * @param  num 当前数
 * @param  total 总数
 */
function getPercent(num, total){
    num = parseFloat(num);
    total = parseFloat(total);
    if (isNaN(num) || isNaN(total)) {
        return "-";
    }
    // Math.round 返回一个数字四舍五入后最接近的整数
    return total <= 0? "0%" : Math.round((num / total) * 10000) / 100.0 + "%";
}

// 向sessionStorage设置参数。如果key相同，会用逗号拼接，按需使用
function setSessionStorage(key, value) {
    let noStr = sessionStorage.getItem(key);
    if (null == noStr || '' == noStr){
        sessionStorage.setItem(key, value);
        return;
    }
    let noArr = noStr.split(',');
    if (noArr.indexOf(value) == -1){
        noStr = noStr+','+value;
        sessionStorage.setItem(key, noStr);
    }
}

// 获取sessionStorage参数
function getSessionStorage(key) {
    let noStr = sessionStorage.getItem(key);
    return noStr;
}

// 删除sessionStorage指定参数
function delSessionStorage(key) {
    sessionStorage.removeItem(key);
}

//获取指定日期距当前日期时间差
function getDiffDate(targetDate) {
    let date1 = new Date(targetDate);
    let date2 = new Date();
    date1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate());
    date2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());
    const diff = date2.getTime() - date1.getTime();
    const diffDate = diff / (24 * 60 * 60 * 1000);
    return diffDate;
}

//获取指定日期时间差 yyyy-MM-dd
function getDiffDate2(date_pre, date_next) {
    let strSeparator = "-"; //日期分隔符
    let oDate1;
    let oDate2;
    let iDays;
    oDate1 = date_pre.split(strSeparator);
    oDate2 = date_next.split(strSeparator);
    let strDateS = new Date(oDate1[0], oDate1[1] - 1, oDate1[2]);
    let strDateE = new Date(oDate2[0], oDate2[1] - 1, oDate2[2]);
    iDays = parseInt(Math.abs(strDateS - strDateE) / 1000 / 60 / 60 / 24)//把相差的毫秒数转换为天数
    return iDays;
}

//计算指定日期相差小时数 yyyy-MM-dd hh:mm:ss
function getTimeDiff(d1, d2){
    let dateBegin = new Date(d1);
    let dateEnd = new Date(d2);
    // 计算出毫秒数
    let dateDiff = dateEnd.getTime() - dateBegin.getTime();
    let hours=Math.floor(dateDiff/(3600*1000))//计算出小时数
    return hours
}

//计算指定日期相差天数 yyyy-MM-dd hh:mm:ss
function getDayDiff(d1, d2){
    let dateBegin = new Date(d1);
    let dateEnd = new Date(d2);
    // 计算出毫秒数
    let dateDiff = dateEnd.getTime() - dateBegin.getTime();
    let dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000));//计算出相差天数
    return dayDiff;
}

jQuery.fn.shake = function(intShakes /*Amount of shakes*/, intDistance /*Shake distance*/, intDuration /*Time duration*/) {
    this.each(function() {
        var jqNode = $(this);
        jqNode.css({position: 'relative'});
        for (var x=1; x<=intShakes; x++) {
            jqNode.animate({ left: (intDistance * -1) },(((intDuration / intShakes) / 4)))
                .animate({ left: intDistance },((intDuration/intShakes)/2))
                .animate({ left: 0 },(((intDuration/intShakes)/4)));
        }
    });
    return this;
}

// 判断访问设备是PC端还是移动端
function isPC(){
    let sUserAgent = navigator.userAgent.toLowerCase();
    let bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
    let bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
    let bIsMidp = sUserAgent.match(/midp/i) == "midp";
    let bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
    let bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
    let bIsAndroid = sUserAgent.match(/android/i) == "android";
    let bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
    let bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";

    if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {//如果是上述设备就会以移动设备打开
        return false;
    }else{//否则就是电脑端打开
        return true;
    }
}

/**
 * 将数字转换为中文(金额)
 * @param num
 * @returns {string}
 */
function chineseNumber(num)
{
    if (isNaN(num) || num > Math.pow(10, 12))
        return ""
    var cn = "零壹贰叁肆伍陆柒捌玖"
    var unit = new Array("拾佰千", "分角")
    var unit1 = new Array("万亿", "")
    var numArray = num.toString().split(".")
    var start = new Array(numArray[0].length - 1, 2)

    function toChinese(num, index)
    {
        var num = num.replace(/\d/g, function($1)
        {
            return cn.charAt($1) + unit[index].charAt(start-- % 4 ? start % 4 : -1)
        })
        return num
    }

    for (var i = 0; i < numArray.length; i++)
    {
        var tmp = ""
        for (var j = 0; j * 4 < numArray[i].length; j++)
        {
            var strIndex = numArray[i].length - (j + 1) * 4
            var str = numArray[i].substring(strIndex, strIndex + 4)
            var start = i ? 2 : str.length - 1
            var tmp1 = toChinese(str, i)
            tmp1 = tmp1.replace(/(零.)+/g, "零").replace(/零+$/, "")
            tmp1 = tmp1.replace(/^壹拾/, "拾")
            tmp = (tmp1 + unit1[i].charAt(j - 1)) + tmp
        }
        numArray[i] = tmp
    }

    numArray[1] = numArray[1] ? numArray[1] : ""
    numArray[0] = numArray[0] ? numArray[0] + "元" : numArray[0], numArray[1] = numArray[1].replace(/^零+/, "")
    numArray[1] = numArray[1].match(/分/) ? numArray[1] : numArray[1] + "整"
    return numArray[0] + numArray[1]
}


document.onclick = (event) => {
    sessionStorage.setItem("logintime", new Date().getTime());

}
